<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <button>获取数据</button>
    <script>
        // 1. 定义ajax函数 
        function ajax(url){
            // 1.1 返回new Promise()对象
            return new Promise((res,rej)=>{
                // 1.1 创建xhr对象
                let x =new XMLHttpRequest();
                // 1.2 open
                x.open('get',url)
                // 1.3 send
                x.send()
                x.responseType = 'json';
                // 1.4 事件监听
                x.onreadystatechange = function(){

                    // console.log(x.readyState);
                    // if(x.readyState === 4 && x.status ===200){
                    //     res(x.response)
                    // }else{
                    //     rej(x.status)
                    // }   

                    if(x.readyState === 4){
                        if(x.status>=200 && x.status<300){
                            res(x.response)
                        }else{
                            rej(x.status)
                        }
                    }
                }
            })
        }
        // 2. 获取按钮
        let btn = document.querySelector('button')
        // 3. 添加点击事件
        btn.onclick = function(){
            // 3.1 调用ajax方法
            ajax('https://v1.hitokoto.cn/?c=a')
            .then(val=>{
                console.log(val);
            },(rea)=>{
                console.log(rea);
            })

        }
    
    </script>
</body>

</html>